<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>首页 - 日记本</title>
    <meta charset="UTF-8" />
    <style>
        body {
            font-family: "Segoe UI", sans-serif;
            max-width: 800px;
            margin: 30px auto;
            background: #f9f9f9;
            color: #333;
        }

        h1, h2, h3 {
            color: #2c3e50;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }

        table, th, td {
            border: 1px solid #ccc;
        }

        th, td {
            padding: 10px;
            text-align: left;
        }

        th {
            background-color: #f0f0f0;
        }

        button {
            padding: 6px 12px;
            margin: 4px;
            border: none;
            background-color: #3498db;
            color: white;
            cursor: pointer;
            border-radius: 4px;
            transition: background-color 0.2s ease;
        }

        button:hover {
            background-color: #2980b9;
        }

        #add-form {
            background: #fff;
            padding: 15px;
            border: 1px solid #ccc;
            border-radius: 6px;
        }

        input[type="text"], textarea {
            width: 100%;
            padding: 8px;
            margin-top: 6px;
            margin-bottom: 12px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
        }

        label {
            font-weight: bold;
        }

        #logoutBtn {
            background-color: #e74c3c;
        }

        #logoutBtn:hover {
            background-color: #c0392b;
        }

        #admin-panel {
            margin: 10px 0;
            background: #fcfcfc;
            border: 1px dashed #aaa;
            padding: 10px;
            border-radius: 4px;
        }

        #showAddFormBtn {
            margin-top: 10px;
        }
    </style>
</head>
<body>
<h1>欢迎来到日记本首页</h1>

<p>当前用户：<span id="username">加载中...</span></p>

<div id="admin-panel" style="display:none;">
    <button id="loadAllDiariesBtn">查看所有日记（管理员）</button>
</div>

<h2>你的日记列表</h2>
<table border="1" id="diary-table">
    <thead>
    <tr>
        <th>标题</th>
        <th>内容</th>
        <th>操作人</th>
        <th>操作时间</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody id="diary-tbody">
    <tr><td colspan="3">加载中...</td></tr>
    </tbody>
</table>

<button id="showAddFormBtn">新建日记</button>

<!-- 新建日记表单 -->
<div id="add-form" style="display:none; margin-top: 20px;">
    <h3>新建日记</h3>
    <label>标题：<input type="text" id="newTitle"></label><br/>
    <label>内容：<textarea id="newContent" rows="4" cols="50"></textarea></label><br/>
    <button id="addDiaryBtn">提交</button>
    <button id="cancelAddBtn">取消</button>
</div>

<p><button id="logoutBtn">退出登录</button></p>

<script>
    const token = localStorage.getItem("token");

    if (!token) {
        alert("未登录，请先登录");
        location.href = "/view/toLogin";
    }

    // 解析JWT简易获取用户名
    function parseJwt(token) {
        try {
            const base64Url = token.split('.')[1];
            const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
            return JSON.parse(window.atob(base64));
        } catch (e) {
            return null;
        }
    }

    const payload = parseJwt(token);
    if (payload) {
        document.getElementById("username").textContent = payload.sub || "未知用户";
        if ((payload.auth || payload.authorities || payload.role || "").toUpperCase().includes("ADMIN")) {
            document.getElementById("admin-panel").style.display = "block";
        }
    }

    // 载入当前用户日记
    async function loadMyDiaries() {
        const res = await fetch("/diaries", {
            headers: { "Authorization": "Bearer " + token }
        });
        if (res.ok) {
            const diaries = await res.json();
            console.log('dadad',diaries)
            renderDiaryTable(diaries);
        } else {
            alert("加载日记失败");
            setTimeout(() => location.href = "/view/toLogin", 500);
        }
    }

    // 渲染日记列表
    function renderDiaryTable(diaries) {
        const tbody = document.getElementById("diary-tbody");
        tbody.innerHTML = "";
        if (!diaries.length) {
            tbody.innerHTML = `<tr><td colspan="3">你还没有日记，快去新建一个吧！</td></tr>`;
            return;
        }
        diaries.forEach(diary => {
            const tr = document.createElement("tr");
            tr.innerHTML = `
                <td>${escapeHtml(diary.title)}</td>
                <td>${escapeHtml(diary.content)}</td>
                <td>${escapeHtml(diary.updatedBy)}</td>
                <td>${escapeHtml(diary.updatedTime)}</td>
                <td>
                    <button onclick="editDiary(${diary.id}, '${escapeJs(diary.title)}', '${escapeJs(diary.content)}')">编辑</button>
                    <button onclick="deleteDiary(${diary.id})">删除</button>
                </td>`;
            tbody.appendChild(tr);
        });
    }

    // 转义HTML
    function escapeHtml(text) {
        return text
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }

    // 转义JS字符串，防止引号断开
    function escapeJs(text) {
        return text.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
    }

    // 删除日记
    async function deleteDiary(id) {
        if (!confirm("确定删除该日记吗？")) return;
        const res = await fetch("/diaries/" + id, {
            method: "DELETE",
            headers: { "Authorization": "Bearer " + token }
        });
        if (res.ok) {
            alert("删除成功");
            loadMyDiaries();
        } else {
            alert("删除失败");
        }
    }

    // 编辑日记弹窗（简单prompt版）
    function editDiary(id, title, content) {
        const newTitle = prompt("编辑标题", title);
        if (newTitle === null) return;
        const newContent = prompt("编辑内容", content);
        if (newContent === null) return;

        fetch("/diaries/" + id, {
            method: "PUT",
            headers: {
                "Authorization": "Bearer " + token,
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ title: newTitle, content: newContent })
        }).then(res => {
            if (res.ok) {
                alert("更新成功");
                loadMyDiaries();
            } else {
                res.text().then(text => alert("更新失败：" + text));
            }
        });
    }

    // 新建日记按钮事件
    document.getElementById("showAddFormBtn").onclick = () => {
        document.getElementById("add-form").style.display = "block";
    };
    document.getElementById("cancelAddBtn").onclick = () => {
        document.getElementById("add-form").style.display = "none";
        clearAddForm();
    };

    // 新建日记提交
    document.getElementById("addDiaryBtn").onclick = async () => {
        const title = document.getElementById("newTitle").value.trim();
        const content = document.getElementById("newContent").value.trim();
        if (!title || !content) {
            alert("标题和内容不能为空");
            return;
        }
        const res = await fetch("/diaries", {
            method: "POST",
            headers: {
                "Authorization": "Bearer " + token,
                "Content-Type": "application/json"
            },
            body: JSON.stringify({ title, content })
        });
        if (res.ok) {
            alert("添加成功");
            document.getElementById("add-form").style.display = "none";
            clearAddForm();
            loadMyDiaries();
        } else {
            const err = await res.text();
            alert("添加失败：" + err);
        }
    };

    function clearAddForm() {
        document.getElementById("newTitle").value = "";
        document.getElementById("newContent").value = "";
    }

    // 管理员查看所有日记
    document.getElementById("loadAllDiariesBtn").onclick = async () => {
        const res = await fetch("/diaries/all", {
            headers: { "Authorization": "Bearer " + token }
        });
        if (res.ok) {
            const diaries = await res.json();
            renderDiaryTable(diaries);
        } else if (res.status === 403) {
            alert("无权限查看所有日记");
        } else {
            alert("加载所有日记失败");
        }
    };

    // 退出登录
    document.getElementById("logoutBtn").onclick = () => {
        localStorage.removeItem("token");
        location.href = "/view/toLogin";
    };

    // 初始化加载我的日记
    loadMyDiaries();

</script>
</body>
</html>
